//组合式API
import { defineStore } from "pinia";
import { ref, computed, reactive } from "vue";
import { login, getMenu, logout } from "@/api/user";
import { ACCESS_TOKEN, USER_INFO, USER_MENU } from "@/store/mutation-types";
const useUserStore = defineStore("user", () => {
  //存储数据
  let token = ref("");
  let info: any = reactive({});
  let menu: any = reactive([]);

  //计算属性
  let token_computed = computed(() => {
    return token.value != "" ? token.value : localStorage.getItem(ACCESS_TOKEN);
  });

  let info_computed = computed(() => {
    let storage_info = localStorage.getItem(USER_INFO) as string;
    return info.value ? info.value : JSON.parse(storage_info);
  });

  let menu_computed = computed(() => {
    let storage_menu = localStorage.getItem(USER_MENU) as string;
    return menu.value ? menu.value : JSON.parse(storage_menu);
  });

  //方法(加上async返回的一定是一个promise)
  let handleLogin = async (userInfo: any) => {
    try {
      let result = await login(userInfo);
      if (result.code == 200) {
        token.value = result.data.token;
        info.value = result.data;
        localStorage.setItem(ACCESS_TOKEN, token.value);
        localStorage.setItem(USER_INFO, JSON.stringify(info.value));
        console.log("token", token);
        console.log("info", info);
        return "ok";
      } else {
        return Promise.reject(result.message);
      }
    } catch (error) {
      return Promise.reject(error);
    }
  };
  //获取当前登录用户所有菜单
  let getUserMenu = async () => {
    try {
      let result = await getMenu();
      if (result.code == 200) {
        menu.value = result.data;
        localStorage.setItem(USER_MENU, JSON.stringify(result.data));
      } else {
        return Promise.reject("获取用户信息失败," + result.message);
      }
    } catch (error) {
      return Promise.reject(error);
    }
  };
  //处理用户退出
  let handleLogout = async () => {
    try {
      let result = await logout();
      if (result.code == 200) {
        token.value = "";
        info.value = {};
        menu.value = [];
        localStorage.removeItem(ACCESS_TOKEN);
        localStorage.removeItem(USER_INFO);
        localStorage.removeItem(USER_MENU);
      } else {
        return Promise.reject("退出失败," + result.message);
      }
    } catch (error) {
      return Promise.reject(error);
    }
  };
  return {
    token,
    info,
    token_computed,
    info_computed,
    menu_computed,
    handleLogin,
    getUserMenu,
    handleLogout,
  };
});

//向外暴露
export default useUserStore;
